package net.wicp.tams.common.redis.pool;

import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

public class JedisSentinelPoolTams extends AbsPool {
	private volatile JedisSentinelPool jedisSentinelPool;

	public JedisSentinelPoolTams() {
	}

	public JedisSentinelPoolTams(String masterName, Set<String> sentinels,
			final GenericObjectPoolConfig<Jedis> poolConfig, final int timeout) {
		poolConfig.setJmxEnabled(true);
		poolConfig.setJmxNamePrefix("jedis-pool");
		// 第一个timeout Jedis连接超时(单位:毫秒)，第二个timeout读写超时(单位:毫秒)
		JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(masterName, sentinels, poolConfig, timeout, timeout,
				StringUtil.hasNull(Conf.get("common.redis.redisserver.password"), null),
				Conf.getInt("common.redis.redisserver.defaultDb"), Conf.get("common.redis.redisserver.clientName"));
		setJedisSentinelPool(jedisSentinelPool);
	}

	public void setJedisSentinelPool(JedisSentinelPool jedisSentinelPool) {
		doLeak(jedisSentinelPool);
		this.jedisSentinelPool = jedisSentinelPool;
	}

	@Override
	public Jedis getResource() {
		return this.jedisSentinelPool.getResource();
	}

	@Override
	public void destroy() {
		this.jedisSentinelPool.destroy();
		this.jedisSentinelPool = null;
	}

	@Override
	public boolean isInit() {
		return this.jedisSentinelPool != null;
	}

}
